<?php 
function callwiki($query){
$url = 'http://en.wikipedia.org/w/api.php';
$param = 'action=parse&section=0&format=json&disablepp=1&prop=text|revid&page='.urlencode($query);
$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";

$ch = curl_init($url);    

curl_setopt ($ch, CURLOPT_POST, 1);      
curl_setopt ($ch, CURLOPT_POSTFIELDS, $param);     
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);     
$wikiout = json_decode(curl_exec ($ch),true);      
curl_close ($ch);  
return $wikiout;
}

if(isset($_POST['api'])):
include('../../../wp-blog-header.php');
global $wpdb;

$my_id = $_POST['pageid'];
$res = $wpdb->get_row("SELECT * FROM institution_table WHERE institution_id = $my_id LIMIT 1",ARRAY_A);
//print_r($res);
//exit();
$name = $res['name'];
$long = $res['long_name'];
$dist = $res['district_name'];
$reg = $res['region_name'];
$city = $res['city_name'];
$ward = $res['ward_no'];
$beds = $res['beds'];
//echo "<br />";
//$wpdb->print_error();
?>
<h1 class="titlehead"><?php echo $name;?></h1>
<div id="pulldatabox">
	<div id="statOverview">
		<h4><?php echo $long;?></h4>
		<p>
		<?php echo $city.', Ward #'.$ward.', '.$dist; ?><br />
		<?php echo $reg; ?>
		</p>
		<h4>Beds</h4>
		<p><?php echo $beds; ?></p>
	</div>
	<div id="pullwikitable">
		<?php 
		$wikitext = '';
		$wikihead = '';
		
		$cityFword = $city;
		if(strpos($city,' ') != false){
			$citywords = explode(' ',$city);
			$cityFword = $citywords[0];
		}
		$wikiout = callwiki($cityFword);
		$revid = $wikiout['parse']['revid'];
		$wikihead = '<h4>About: '.$city.'</h4>';

		if($revid == 0){
			$wikihead = '<h4>About: '.$dist.' District</h4>';
			
			$wikiout = callwiki($dist.'_District');
			$revid = $wikiout['parse']['revid'];
			if($revid == 0){
			$wikiout = '';
			$wikihead = '';
			}
		}

		$citerr = '<strong class="error">Cite error: There are <code>&lt;ref&gt;</code> tags on this page, but the references will not show without a <code>{{Reflist}}</code> template or a <code>&lt;references /&gt;</code> tag; see the <a target="_blank" href="http://en.wikipedia.org/wiki/Help:Cite_errors/Cite_error_refs_without_references" title="Help:Cite errors/Cite error refs without references">help page</a>.</strong>';
		if(is_array($wikiout)){
		$wikitext = str_replace($citerr, '', $wikiout['parse']['text']['*']);
		$wikitext = str_replace('<a href="/wiki','<a target="_blank" href="http://en.wikipedia.org/wiki', $wikitext);
		$wikitext = $wikihead . $wikitext;
		}
		echo $wikitext;
		?>
	</div>
</div>
<div class="clear"> </div>
<?php endif; ?>
